package com.sunlands.qdcy.tongzhuo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>redis客户端配置</p>
 * <PRE>
 * @author zl
 * @version 1.0
 * @package: com.sunlands.zlcx.mpmsgservice.config
 * @date Created in 2017/11/30 15:32
 * @copyright: Copyright (c) founders
 */
@Configuration
@EnableCaching
public class RedisConfig {

    /**
     * 注解里的字符串值必须使用字面量或者常量,所以单独定义常量, 同时用在注解和Cache定义中
     */
    public static class CacheKeys {
        private CacheKeys() {
        }
        public static final String TOPIC_RECOMMEND = "tz-user-diary:topic:recommend";
        public static final String TOPIC_HISTORY = "tz-user-diary:topic:history";
        public static final String TOPIC_ATTENTION = "tz-user-diary:topic:attention";
        public static final String TOPIC_ID = "tz-user-diary:topic:id";
        public static final String DIARY_BY_ID = "tz-user-diary:diary:by-id";
        public static final String DIARY_DETAIL_BY_ID = "tz-user-diary:diary:detail:by-id";
        public static final String CHECK_DIARY = "tz-user-diary:diary:check-diary";
    }

    /**
     * 这里记录cache key和过期时间
     */
    private enum CacheEnum {

        /**
         *
         */
        TOPIC_RECOMMEND(RedisConfig.CacheKeys.TOPIC_RECOMMEND, 60 * 1),
        DIARY_BY_ID(RedisConfig.CacheKeys.DIARY_BY_ID, 60 * 2),
        DIARY_DETAIL_BY_ID(RedisConfig.CacheKeys.DIARY_DETAIL_BY_ID, 60),
        ;

        public final String cacheName;
        public final int expireInSeconds;

        CacheEnum(String cacheName, int expireInSeconds) {
            this.cacheName = cacheName;
            this.expireInSeconds = expireInSeconds;
        }
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setUsePrefix(true);
        cacheManager.setDefaultExpiration(60);

        Map<String, Long> expires = Arrays.stream(RedisConfig.CacheEnum.values())
                .collect(Collectors.toMap(e -> e.cacheName, e -> Long.valueOf(e.expireInSeconds)));

        cacheManager.setExpires(expires);

        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.setSerializationInclusion(Include.NON_NULL);
        om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        return container;
    }

    static class StringRedisSerializer implements RedisSerializer<Object> {
        private final Charset charset;

        public StringRedisSerializer() {
            this(Charset.forName("UTF8"));
        }

        public StringRedisSerializer(Charset charset) {
            Assert.notNull(charset, "Charset must not be null!");
            this.charset = charset;
        }
        @Override
        public String deserialize(byte[] bytes) {
            return (bytes == null ? null : new String(bytes, charset));
        }
        @Override
        public byte[] serialize(Object object) {
            return (object == null ? null : object.toString().getBytes(charset));
        }
    }

}
